package org.jeecg.modules.xxgx.sjtb.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.SpringContextUtils;
import org.jeecg.modules.xxgx.sjtb.vo.SjtbApiResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
public class SjtbRequestUtil {

    private final static String tokenKeyPrix="SYNCDATA-SERVER-TOKEN";//存放在redis缓存里面的token

    private final static long tokenTime=3300;//存放在redis缓存里面的token

    RedisUtil redisUtil;

    private String serverUrl;
    private String appKey;
    private String appSecret;

    public String getServerUrl() {
        return serverUrl;
    }

    public void setServerUrl(String serverUrl) {
        this.serverUrl = serverUrl;
    }

    public String getAppKey() {
        return appKey;
    }

    public void setAppKey(String appKey) {
        this.appKey = appKey;
    }

    public String getAppSecret() {
        return appSecret;
    }

    public void setAppSecret(String appSecret) {
        this.appSecret = appSecret;
    }

    public SjtbRequestUtil(){
        redisUtil = SpringContextUtils.getBean(RedisUtil.class);
    }
    public String token() {
        String token=null;
        String tokenKey = tokenKeyPrix + appKey;
        token =redisUtil.get(tokenKey)!=null?String.valueOf(redisUtil.get(tokenKey)):null;
        if(StringUtils.isEmpty(token)) {
            token = tokenGet();
            if(StringUtils.isNotEmpty(token)) {
                redisUtil.set(tokenKey, token, tokenTime);
            }
        }
        return token;
    }

    /**
     * 获取token
     * @return
     */
    public String tokenGet() {
        String serverUrl = getServerUrl();
        if(StringUtils.isEmpty(serverUrl)) {
            return null;
        }
        String url = serverUrl + "/api/comApi/getToken";

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("app_key",getAppKey());
        jsonObject.put("app_secret",getAppSecret());

        String result = doPostJson(url, jsonObject.toJSONString());

        String token = "";
        SjtbApiResponse sjtbApiResponse = JSONObject.parseObject(result,SjtbApiResponse.class);
        if(sjtbApiResponse.isSuccess()){
            JSONObject rtnJson = sjtbApiResponse.getResult();
            token = rtnJson.getString("token");
        } else {
            log.error("数据同步接口获取token失败：" + sjtbApiResponse.getMessage());
        }
        return token;
    }

    public SjtbApiResponse request(String url, String jsonStr) {
        if(!url.toLowerCase().startsWith("http") ){
            url = getServerUrl() + url;
        }
        Map<String, Object> headerMap = new HashMap<>();
        String token = token();
        if(StringUtils.isEmpty(token)){
            SjtbApiResponse sjtbApiResponse = new SjtbApiResponse();
            sjtbApiResponse.setCode(401);
            sjtbApiResponse.setSuccess(false);
            sjtbApiResponse.setMessage("获取token失败");
            return sjtbApiResponse;
        }
        headerMap.put("X-Access-Token", token);
        String result = doPostJson(url, jsonStr, headerMap);
        SjtbApiResponse sjtbApiResponse = JSONObject.parseObject(result,SjtbApiResponse.class);

        if(sjtbApiResponse.getCode().equals(401)) {//token失效
            String tokenKey = tokenKeyPrix + appKey;
            redisUtil.del(tokenKey);
            return this.request(url,jsonStr);
        } else {
            return sjtbApiResponse;
        }
    }

    private String doPostJson(String url, String json) {
        return doPostJson(url, json, null);
    }
    private String doPostJson(String url, String json, Map<String, Object> headerMap) {
        // 创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);

            if(headerMap != null) {
                Iterator<String> it = headerMap.keySet().iterator();
                while(it.hasNext()){
                    String key = it.next();
                    String value = String.valueOf(headerMap.get(key));
                    httpPost.setHeader(key,value);
                }
            }

            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            if (response == null) {
                log.info("http请求url{}异常，返回结果null,", url);
                return null;
            }
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return resultString;
    }
}
